<template>
  <page-header-wrapper>
    <a-result title="该功能暂未开放" @click="notopened" style="padding-top: 120px">
      <template #extra>
      </template>
    </a-result>
    <div style="display:none">
      <a-card :bordered="false">
        <a-icon type="menu-fold" @click="turnSmall" class="turnSmall" v-if="treespan===4"></a-icon>
        <a-icon type="menu-unfold" @click="turnSmall" class="turnSmall" v-if="treespan===0"/>
        <a-row :gutter="13">
          <a-col :span="treespan">
            <a-skeleton active :paragraph="{ rows: 5 }" :loading="menuLoading" />
            <s-tree
              :dataSource="orgTree"
              :openKeys="openKeys"
              :search="false"
              @click="handleClick"
              @titleClick="handleTitleClick"
              :selectKey="defaultSelectKey">
            </s-tree>
          </a-col>
          <a-col :span="tablespan">
            <!-- <a-skeleton active :paragraph="{ rows: 5 }" :loading="menuLoading" /> -->
            <!-- <a-button type="primary" v-if="!menuLoading" style="margin-bottom:10px" @click="handleAdd">新增</a-button> -->
            <a-table
              ref="table"
              size="default"
              :loading="loading"
              :columns="columns"
              :data-source="dataSource"
              :alert="false"
              :pagination="pagination"
              @change="handlePageChange"
            >
              <div
                slot="filterDropdown"
                slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                style="padding: 8px"
              >
                <a-input
                  v-ant-ref="c => (searchInput = c)"
                  :placeholder="`搜索 ${column.dataIndex}`"
                  :value="selectedKeys[0]"
                  style="width: 188px; margin-bottom: 8px; display: block;"
                  @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                  @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
                />
                <a-button
                  type="primary"
                  icon="search"
                  size="small"
                  style="width: 90px; margin-right: 8px"
                  @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
                >
                  搜索
                </a-button>
                <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                  重置
                </a-button>
              </div>
              <a-icon
                slot="filterIcon"
                slot-scope="filtered"
                type="search"
                :style="{ color: filtered ? '#108ee9' : undefined }"
              />
              <template slot="customRender" slot-scope="text, record, index, column">
                <span v-if="searchText && searchedColumn === column.dataIndex">
                  <template
                    v-for="(fragment, i) in text
                      .toString()
                      .split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))"
                  >
                    <mark
                      v-if="fragment.toLowerCase() === searchText.toLowerCase()"
                      :key="i"
                      class="highlight"
                    >{{ fragment }}</mark
                    >
                    <template v-else>{{ fragment }}</template>
                  </template>
                </span>
                <template v-else>
                  {{ text }}
                </template>
              </template>
              <span slot="action" slot-scope="text, record">
                <a href="javascript:;" @click="handleModalData(record)">详情</a>
                <a-divider type="vertical" v-if="record.project_status==1||record.project_status==2" ></a-divider>
                <a-popconfirm
                  v-if="record.project_status==1"
                  title="确定操作?"
                  okText="确定"
                  cancelText="取消"
                  @confirm="() => statusChange(1,2,record)"
                >
                  <a href="javascript:;">受理</a>
                </a-popconfirm>
                <a-popconfirm
                  v-if="record.project_status==2"
                  title="确定操作?"
                  okText="确定"
                  cancelText="取消"
                  @confirm="() => reviewChange(1,4,record)"
                >
                  <a href="javascript:;">评优</a>
                </a-popconfirm>
                <a-divider type="vertical" v-if="record.project_status==1"></a-divider>
                <a-popconfirm
                  v-if="record.project_status==1"
                  title="确定操作?"
                  okText="确定"
                  cancelText="取消"
                  @confirm="() => statusChange(1,3,record)"
                >
                  <a href="javascript:;">退件</a>
                </a-popconfirm>
              </span>
            </a-table>
          </a-col>
        </a-row>
        <a-modal
          :visible="visible"
          @cancel="handleModalClose()"
          @ok="handleModalOk()"
          title="详情"
          :confirm-loading="confirmLoading"
          okText="保存"
          cancelText="取消"
          width="65%"
          :footer="null"
          v-if="visible"
          :maskClosable="false"
        >
          <a-skeleton active :paragraph="{ rows: 8 }" :loading="detailLoading" />
          <a-form-model
            ref="showData"
            :label-col="{span: 5}"
            :wrapper-col="{span: 18}"
            :model="showData"
          >
            <a-form-model-item
              v-for="(item, index) in showData.domains"
              :key="index"
              :label="item.label_name"
              :prop="'domains.' + index + '.value'"
              :rules="[{ required: item.required, message: '内容不可为空', trigger: 'change' },{required: item.required, message: '内容不可为空', trigger: 'blur'}]"
              :style="{ display: item.type_id!=3 ? 'inline-block' : 'block', width: item.type_id!=3 ? 'calc(50% - 12px)':'100%'}"
              :label-col="{span: item.type_id==3 ? 2:5}"
            >
              <a-input
                v-if="item.type_id==1"
                :disabled="item.disabled"
                v-model="item.value"
                :placeholder="item.placeHolder"
              />
              <a-select v-if="item.type_id==2" :disabled="item.disabled" v-model="item.value">
                <template v-for="(list, listIndex) in item.selectionList">
                  <a-select-option :key="listIndex" :value="list">
                    {{ list }}
                  </a-select-option>
                </template>
              </a-select>
              <a-upload
                :file-list="item.value"
                v-if="item.type_id==3"
                :disabled="item.disabled"
                list-type="picture-card"
                @preview="handlePreview"
              >
                <!-- <a-button> <a-icon type="upload" /> 点击上传 </a-button> -->
              </a-upload>
              <a-date-picker
                v-model="item.value"
                v-if="item.type_id==4"
                :disabled="item.disabled"
                type="date"
                valueFormat="YYYY/MM/DD"/>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" v-if="previewVisible" width="35%">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        <a-modal
          :visible="reviewmajor"
          v-if="reviewmajor"
          @ok="handleOkreview"
          @cancel="handleCancelreview"
          title="选择评优专业"
          width="50%"
        >
          <a-form-model ref="reviewselect" :model="reviewselect" :label-col="{span: 9}" :wrapper-col="{span: 10} " :rules="{review: [{ required: true, message: '内容不可为空', trigger: 'blur' }]}">
            <a-form-model-item label="请选择评优专业" prop="review">
              <a-select
                style="width: 100%"
                @change="handleChangereview"
                v-model="reviewselect.review"
              >
                <a-select-option v-for="item in reviewtype" :key="item.id" :value="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
        <org-modal ref="modal" @ok="handleSaveOk" @close="handleSaveClose" />
      </a-card>
    </div>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import STree from '@/components/Tree/Tree'
import { STable } from '@/components'
import OrgModal from '../other/modules/OrgModal'
// import { getServiceList } from '@/api/manage'
// eslint-disable-next-line no-unused-vars
import { menuFinds, workInfoTableHeader, detailFinds, detailEdit, addLabel, addData, projectStatus, getreviewtype, sendreviewtype } from '@/api/mobileReview'

export default {
  name: 'TreeList',
  components: {
    STable,
    STree,
    OrgModal
  },
  data () {
    return {
      originalData: [],
      previewVisible: false,
      previewImage: '',
      reviewmajor: false,
      reviewselect: {},
      reviewselectvalue: '',
      reviewtype: '',
      projectid: '',
      defaultSelectKey: [], // menu默认选中项
      modalStatus: 0, // 状态为0时为新增，为1时为修改
      menuLoading: true,
      searchText: '',
      detailLoading: true,
      showData: { domains: [], projectId: Number },
      confirmLoading: false,
      visible: false,
      projectTypeId: 1,
      loading: true,
      openKeys: [1],
      treespan: 4,
      tablespan: 20,
      dataSource: [],
      projectStatusKey: 1, // 审核状态 0为未申报，1为待受理，2为已受理，3为已退件，4为待评审
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '50']
      },
      // 查询参数
      queryParam: new FormData(),
      // 表头
      columns: [],
      // 加载数据方法 必须为 Promise 对象
      // loadData: parameter => {
      //   var formdata = new FormData()
      //   formdata.append('project_type_id', this.projectTypeId)
      //   formdata.append('project_status', 0)
      //   return workInfoTableHeader(formdata)
      //     .then(res => {
      //       console.log(parameter)
      //       this.columns = res.result.headList
      //       return res.result.data
      //     })
      // },
      orgTree: [],
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  created () {
    this.getMenuInfo()
    this.getrewtype()
  },
  methods: {
    moment,
    handleCancel () {
      this.previewVisible = false
      this.previewImage = ''
    },
    handlePreview (file) {
      this.previewImage = file.url
      this.previewVisible = true
    },
    handleClick (e) {
      console.log('handleClick', e)
      this.projectTypeId = e.keyPath[1] // 父节点Id
      this.projectStatusKey = e.key.charAt(0) // 子节点Id 取拼接后字符串的第一位即为子节点Id
      // this.$refs.table.refresh(true)
      this.getTableData()
    },
    // handleAdd (item) {
    //   console.log('add button, item', item)
    //   this.$message.info(`提示：你点了 ${item.key} - ${item.title} `)
    //   this.$refs.modal.add(item.key)
    // },
    handleTitleClick (item) {
      console.log('handleTitleClick', item)
    },
    titleClick (e) {
      console.log('titleClick', e)
    },
    handleSaveOk () {

    },
    handleSaveClose () {

    },
    getChange () {

    },
    getrewtype () {
      getreviewtype().then(res => {
        if (res.code === 200) {
          this.reviewtype = res.result
        } else {
          this.$message.error('获取评审评优专业类别失败')
        }
      })
    },
    handleOkreview () {
      this.$refs.reviewselect.validate(valid => {
        if (!valid) {
          return false
        } else {
          var fdproject = new FormData()
          fdproject.append('project_id', this.projectid.project_id)
          fdproject.append('review_major', this.reviewselectvalue)
          sendreviewtype(fdproject).then(res => {
            if (res.code === 200) {
              this.statusChange(1, 4, this.projectid)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    handleCancelreview () {
      this.reviewmajor = false
      this.projectid = ''
    },
    handleChangereview (value) {
      this.reviewselectvalue = value
    },
    // 获取左侧树状信息
    getMenuInfo () {
      // this.loading = true
      var treeKids = [ { title: '待受理', key: '1' }, { title: '已受理', key: '2' }, { title: '已退件记录', key: '3' }, { title: '待评审', key: '4' } ]
      this.menuLoading = true
      menuFinds().then(res => {
        this.orgTree = res.result
      // 构造函数
        function SonObj (title, key) {
          this.title = title
          this.key = key
        }
        // 将四种状态push进menu数组，并将父节点Id与子节点Id拼接成为新的子节点Id 防止选择menu项时同时选中
        this.orgTree.forEach((item) => {
          item['children'] = []
          treeKids.forEach(ele => {
            item['children'].push(new SonObj(ele.title, ele.key + item.key))
          })
        })
        console.log(this.orgTree)
        this.openKeys[0] = this.orgTree[0].key
        this.defaultSelectKey[0] = this.orgTree[0].children[0].key
        // 获取menu后表格默认显示第一个menu的数据
        this.projectTypeId = this.orgTree[0].key
        this.projectStatusKey = '1'
        this.getTableData()
        this.menuLoading = false
        // this.loading = false
      })
    },
    // 列搜索
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    // 列搜索重置
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    // 对动态请求到的表头数组遍历插入列搜索相关slot及函数 详见ant design vue文档
    headerPush (data) {
      data.forEach(item => {
        item['scopedSlots'] = { filterDropdown: 'filterDropdown', filterIcon: 'filterIcon', customRender: 'customRender' }
        item['onFilter'] = (value, record) =>
            record[item.dataIndex]
              .toString()
              .toLowerCase()
              .includes(value.toLowerCase())
        item['onFilterDropdownVisibleChange'] = visible => {
          if (visible) {
            setTimeout(() => {
              this.searchInput.focus()
            }, 0)
          }
        }
      })
    },
    // 获取表头及数据
    getTableData () {
      this.loading = true
      var formdata = new FormData()
      formdata.append('project_type_id', this.projectTypeId)
      formdata.append('project_status', this.projectStatusKey)
      workInfoTableHeader(formdata).then(res => {
        this.columns = res.result.headList
        // 已受理页面增加受理时间列
        // eslint-disable-next-line eqeqeq
        if (this.projectStatusKey == 2) {
          this.columns.push({ title: '受理时间', dataIndex: 'audit_time' })
        }
        this.headerPush(this.columns)
        // console.log(this.columns)
        this.columns.push({ title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, key: 'action', fixed: 'right' })
        this.originalData = res.result.data.data
        this.dataSource = res.result.data.data
        this.pagination.total = res.result.data.total
        this.loading = false
      })
    },
    // handleChange (pagination) {
    //   this.queryParam.pageNo = pagination.current
    //   this.queryParam.pageSize = pagination.pageSize
    //   console.log('????')
    //   this.$refs.table.refresh(true)
    // },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 左侧树状菜单收缩
    turnSmall () {
      this.tablespan === 20 ? this.tablespan = 24 : this.tablespan = 20
      this.treespan === 0 ? this.treespan = 4 : this.treespan = 0
    },
    // 点击详情时获取模态框信息
    handleModalData (record) {
      this.modalStatus = 1
      this.visible = true
      this.detailLoading = true
      // console.log(record)
      var fd = new FormData()
      fd.append('project_id', record.project_id)
      detailFinds(fd).then(res => {
        this.showData.domains = res.result
        this.showData.domains.forEach(item => {
          // eslint-disable-next-line eqeqeq
          if (item.type_id == 3) {
            item['value'].forEach(ele => {
              ele['url'] = ele.file_url
              ele['name'] = ele.file_id
              ele['status'] = 'done'
              ele['uid'] = ele.file_id
            })
          }
        })
        this.showData.projectId = record.project_id
        this.detailLoading = false
        // console.log(this.showData)
      })
    },
    // 点击新增时获取模态框信息
    handleAdd () {
      this.modalStatus = 0
      this.visible = true
      this.detailLoading = true
      var fd = new FormData()
      fd.append('project_type_id', this.projectTypeId)
      addLabel(fd).then(res => {
        var data = res.result
        // 新增是disabled全为false
        data.forEach(item => {
          item['disabled'] = false
        })
        this.showData.domains = data
        this.detailLoading = false
      })
    },
    handleModalClose () {
      this.visible = false
      this.showData.domains = []
    },
    // 模态框保存
    handleModalOk () {
      this.$refs['showData'].validate(valid => {
        if (!valid) {
          return false
        } else {
          if (this.modalStatus === 1) {
            this.confirmLoading = true
            var request = {
              'project_id': this.showData.projectId,
              'valueList': this.showData.domains
            }
            detailEdit(request).then(res => {
              this.confirmLoading = false
              this.$notification.success({
                title: '成功',
                message: res.message
              })
              this.getTableData()
              this.handleModalClose()
            }).catch(err => {
              this.$notification.error({
                title: '失败',
                message: err.message
              })
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = true
            var requestAdd = {
              'project_type_id': this.projectTypeId,
              'headList': this.showData.domains
            }
            addData(requestAdd).then(res => {
              this.$notification.success({
                title: '成功',
                message: '新增成功'
              })
              this.confirmLoading = false
              this.getTableData()
              this.handleModalClose()
            }).catch(err => {
              this.$notification.error({
                title: '失败',
                message: err.message
              })
              this.confirmLoading = false
            })
          }
        }
      })
    },
    reviewChange (status, enterStatus, record) {
      this.reviewmajor = true
      this.projectid = record
    },
    // 审核及删除 参数0为删除 1为审核
    statusChange (status, enterStatus, record) {
      if (status === 1) {
        var fd = new FormData()
        fd.append('project_id', record.project_id)
        fd.append('project_status', enterStatus)
        fd.append('audit_time', Number(parseInt(new Date().getTime() / 1000)))
        projectStatus(fd).then(res => {
          this.$success({
            title: '操作成功',
            // JSX support
            content: (
              <div>
                <p>您已操作成功</p>
              </div>
            )
          })
          this.handleCancelreview()
          this.getTableData()
        }).catch(err => {
          this.$notification.error({
            title: err.code,
            message: err.message
          })
        })
      }
    },
    // 前端分页
    handlePageChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.dataSource = JSON.parse(JSON.stringify(this.originalData))
      this.dataSource = this.dataSource.slice((this.pagination.current - 1) * this.pagination.pageSize, this.pagination.current * this.pagination.pageSize)
      // console.log(this.dataSource)
    }
  }
}
</script>

<style lang="less" scoped>
  .custom-tree {

    /deep/ .ant-menu-item-group-title {
      position: relative;
      &:hover {
        .btn {
          display: block;
        }
      }
    }

    /deep/ .ant-menu-item {
      &:hover {
        .btn {
          display: block;
        }
      }
    }

    /deep/ .btn {
      display: none;
      position: absolute;
      top: 0;
      right: 10px;
      width: 20px;
      height: 40px;
      line-height: 40px;
      z-index: 1050;

      &:hover {
        transform: scale(1.2);
        transition: 0.5s all;
      }
    }
  }
  .turnSmall{
    cursor: pointer;
    font-size: 20px;
    transition: all 0.3s;
    position: relative;
    top: -10px;
  }
  .turnSmall:hover {
    color: #33AAFF;
    background-color: #F0F2F5;
  }
  // /deep/ .ant-modal-content{
  //   width: 180%;
  //   left: -36%;
  // }
@media screen and (max-width: 500px) {
  /deep/ .ant-modal-content {
    width: 100%;
    left: 0%;
  }
}
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
</style>
